package com.momo.mal.manga.view;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import net.momo.mal.R;
import com.momo.mal.database.MalDatabaseAdapter;
import com.momo.mal.entity.Anime;
import com.momo.mal.entity.Manga;

public class MangaTabImage extends Fragment {
	private ImageView image;
	private MalDatabaseAdapter dbAdapter;
	private JSONObject jsonObject;
	private String mContent = "???";
	
	private static final String KEY_CONTENT = "MangaTabImage:Content";
	
	public static MangaTabImage newInstance(JSONObject jsonObject) {
		MangaTabImage fragment = new MangaTabImage();
		fragment.jsonObject = jsonObject;
		
		return fragment;
	}
	

	@Override
	public void onPause() {
		super.onPause();
		getActivity().getIntent().putExtra("json", jsonObject.toString());
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if(getActivity().getIntent().hasExtra("json")) {
			try {
				jsonObject = new JSONObject(getActivity().getIntent().getStringExtra("json"));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		if(getActivity().getIntent().hasExtra("json")) {
			try {
				jsonObject = new JSONObject(getActivity().getIntent().getStringExtra("json"));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
		if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
            mContent = savedInstanceState.getString(KEY_CONTENT);
        }
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.anime_view_image, null);
		
		dbAdapter = new MalDatabaseAdapter(getActivity());
		image = (ImageView) view.findViewById(R.id.image_anime);
		new RequestImage().execute(jsonObject);
			
		return view;
	}
	
	private class RequestImage extends AsyncTask<JSONObject, Void, Bitmap> {
		
		@Override
		protected Bitmap doInBackground(JSONObject... params) {
			URL url = null;
			Drawable drawable = null;
			Bitmap bitmap = null;
			try {
				if(params[0].has("sync") == true) {
					Manga manga = dbAdapter.getMangaById(params[0].getString("manga_id"));

					String state = Environment.getExternalStorageState();
					File mediaStorageDir = null;
					
					if (Environment.MEDIA_MOUNTED.equals(state)) {
					    mediaStorageDir = new File(getActivity().getExternalCacheDir(), "");
					} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
						mediaStorageDir = new File(getActivity().getCacheDir(), "");
					} else {
					    mediaStorageDir = new File(getActivity().getCacheDir(), "");
					}
					
					File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "manga_" + manga.getId());
					bitmap = BitmapFactory.decodeFile(mediaFile.getAbsolutePath());
				} else {
					url = new URL(params[0].getString("image_url"));
					Object content = url.getContent();
					InputStream stream = (InputStream) content;
//					drawable = Drawable.createFromStream(stream, "src");\
					bitmap = BitmapFactory.decodeStream(stream);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return bitmap;
		}
		
		@Override
		protected void onPostExecute(Bitmap result) {
			image.setImageBitmap(result);
		}
		
	}
}
